import router from '@/router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import getPageTitle from '@/utils/get-page-title'
import { getToken } from '@/utils/auth'
import { useUserStore } from '@/store/user'
import { usePermissionStore } from '@/store/permission'

NProgress.configure({ showSpinner: false })

const whiteList = ['/login', '/404', '/401']

//to:将要进入的页面 vue-router4.0 不推荐使用next()
router.beforeEach(async (to: any) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken()

  const useStore = useUserStore()
  const permissionStore = usePermissionStore()


  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      return '/'
    } else {
      const hasRoles = useStore.roles && useStore.roles.length > 0
      if (hasRoles) {
        return true
      } else {
        try {
          // get user info
          const { roles }: any = await useStore.getInfo()
          // generate accessible routes map based on roles
          const accessRoutes = (await permissionStore.generateRoutes(roles)) as RouterTypes
          
          accessRoutes.forEach(route => {
            router.addRoute(route)
          })

          return { ...to, replace: true }
        } catch (error) {
          await useStore.resetState()
          NProgress.done()
          return `/login?redirect=${to.path}`
        }
      }
    }
  } else {
    // has no token
    if (!whiteList.includes(to.path)) {
      return `/login?redirect=${to.path}`
    } else {
      return true
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})